<template>
  <s-layout title="应急演练">
    <!-- <view class="navbar"></view> -->
    <view class="container">
      <view class="filter-container">
        <!-- 搜索框 -->
        <view class="search-box">
          <view class="search-input-wrapper">
            <fui-icon name="search" :size="36" color="#BDBDBD"></fui-icon>
            <input
              v-model="searchKeyword"
              type="text"
              placeholder="搜索关键字"
              @input="handleSearch"
              class="search-input"
            />
            <view class="clear-btn" v-if="searchKeyword" @tap="clearSearch">
              <fui-icon name="close-fill" :size="28" color="#BDBDBD"></fui-icon>
            </view>
          </view>
        </view>
      </view>

      <view class="list-container">
        <view
          v-for="(item, index) in filteredDrillList"
          :key="index"
          class="drill-card"
          @click="
            sheep.$router.go(`/pages/qy/emergency/detail`, { id: item.id })
          "
        >
          <view class="card-header">
            <view class="header-left">
              <text class="drill-date">{{ item.date }}</text>
            </view>

            <view class="header-right">
              <view
                class="cicon-more"
                style="font-size: 50rpx;
                  left: 430rpx;"
                @click.stop="editBoxShow(item)"
              ></view>

              <!-- This editBox is now tied to the specific item -->
              <view class="editBox" v-if="activeEditItemId === item.id">
                <view
                  class="editBox-item"
                  @click.stop="
                    sheep.$router.go(`/pages/qy/emergency/update`, {
                      id: item.id,
                    });
                    activeEditItemId = null; // Hide menu after clicking
                  "
                >
                  <text class="editBox-item-text">修改</text>
                </view>
                <view class="editBox-item" @click.stop="deleteDetail(item)">
                  <!-- confirmDelete already handles hiding the menu -->
                  <text class="editBox-item-text">删除</text>
                </view>
              </view>
            </view>
          </view>
          <fui-swiper-dot
            :items="item.images"
            :current="current"
            class="drill-image"
          >
            <swiper class="banner-wrap" circular autoplay @change="onChange">
              <swiper-item v-for="img in item.images">
                <image class="banner-image" :src="img" mode="aspectFill" />
              </swiper-item>
            </swiper>
          </fui-swiper-dot>
          <view class="card-body">
            <text class="drill-title">{{ item.title }}</text>
            <view
              class="status-tag"
              :style="{ backgroundColor: item.statusColor }"
            >
              <text :class="statusIcons[item.status]" size="28rpx" />
              {{ item.status }}
            </view>
            <view class="info-grid">
              <view class="info-item">
                <view class="info-content">
                  <text class="info-label cicon-time"> 演练时间</text>
                  <text class="info-value">{{ item.date }}</text>
                </view>
              </view>

              <view class="info-item">
                <view class="info-content">
                  <text class="info-label cicon-location-on">演练地点</text>
                  <text class="info-value">{{ item.address }}</text>
                </view>
              </view>
            </view>

            <view class="meta-row">
              <view class="meta-item">
                <text class="cicon-person" color="#4f4e4e" size="32rpx" />
                <text>参与人数：{{ item.participants }}</text>
              </view>
            </view>

            <view class="duration-box">
              <text>持续时长：{{ item.duration }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <fui-button
      @click="sheep.$router.go('/pages/qy/emergency/update')"
      radius="96rpx"
      btnSize="medium"
      style="
        position: fixed;
        bottom: 50rpx;
        left: 50%;
        transform: translateX(-50%);
        padding: 8px 16px;
        border: none;
        font-size: 30rpx;
      "
      ><text
        class="cicon-add-round-o"
        style="font-size: 40rpx; margin-right: 20rpx"
      ></text>
      <p>添加</p>
    </fui-button>
  </s-layout>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue";
import sheep from "@/sheep";
import { onLoad, onPageScroll, onShow, onUnload } from "@dcloudio/uni-app";


const statusIcons = {
  准备中: "cicon-LightMode",
  进行中: "cicon-whatshot",
  已结束: "cicon-stop",
};
const scrollTop = ref(0);
const emergencyDrillList = ref();
//删除应急演练

const deleteDetail = (item) => {
  // 记录当前滚动位置
  const currentScrollTop = scrollTop.value;
  const params = { dr_id: item.id };
  sheep.$api.qy_emergency.delete(params).then((res) => {
    if (res.code == 200) {
      uni.showToast({
        title: "删除成功",
        icon: "none",
      });
    }
    get();
  });
};

// 用于存储当前显示编辑框的项目的 ID
// 初始化为 null，表示初始时没有任何编辑框显示
const activeEditItemId = ref(null);
// 点击"更多"图标时触发的函数
const editBoxShow = (item) => {
  // 获取被点击项目的 ID
  const currentItemId = item.id;
  // 检查：如果当前点击的项目的编辑框 *已经* 是显示的那个
  if (activeEditItemId.value === currentItemId) {
    // 就将其隐藏（通过将 activeEditItemId 设置回 null）
    activeEditItemId.value = null;
  } else {
    // 否则，显示当前点击项目的编辑框
    // 这会自动隐藏之前可能打开的任何其他项目的编辑框
    activeEditItemId.value = currentItemId;
  }
  console.log("当前显示编辑框的项目 ID:", activeEditItemId.value);
};

// 添加 current 变量
const current = ref(0);

// 添加 onChange 方法
const onChange = (e) => {
  current.value = e.detail.current;
};

// 创建事件监听函数
const handleDataUpdate = () => {
  console.log('列表页收到数据更新事件，准备刷新数据');
  // 使用延迟确保DOM已完全渲染
  setTimeout(() => {
    console.log('开始刷新应急演练列表数据');
    get();
  }, 100); // 短暂延迟确保DOM已渲染
};

// 在onLoad中设置事件监听
onLoad(() => {
  // 注册事件监听
  uni.$on('emergencyDataUpdated', handleDataUpdate);
  get();
});

// 在页面卸载时移除事件监听
onUnload(() => {
  console.log('页面卸载，移除事件监听');
  uni.$off('emergencyDataUpdated', handleDataUpdate);
});

onShow(() => {
  const pages = getCurrentPages();
  console.log("当前页面栈:", pages);
});
onPageScroll((e) => {
  // 传入scrollTop值并触发所有easy-loadimage组件下的滚动监听事件
  scrollTop.value = e.scrollTop;
});
function get() {
  return new Promise((resolve, reject) => {
    const params = {
      company_id: sheep.$store("user").userInfo.company_id,
    };
    sheep.$api.qy_emergency
      .list(params)
      .then((res) => {
        console.log("listData", res);
        emergencyDrillList.value = res.data;
        resolve(); // 数据加载完成后 resolve
      })
      .catch((err) => {
        reject(err); // 如果出错则 reject
      });
  });
}

// 添加搜索相关变量和函数
const searchKeyword = ref("");
const filteredDrillList = computed(() => {
  if (!searchKeyword.value) {
    return emergencyDrillList.value;
  }
  return emergencyDrillList.value.filter((item) =>
    item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

function handleSearch() {
  // 使用计算属性自动过滤
}

function clearSearch() {
  searchKeyword.value = "";
}
</script>
<style lang="scss" scoped>
@import "@/sheep/scss/icon/_coloricon.scss";
.container {
  background: #f7f8fc;
}

/* 筛选区域样式 */
.filter-container {
  background-color: #fff;
  padding-bottom: 10rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.search-box {
  padding: 0rpx 20rpx;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 40rpx;
  padding: 10rpx 24rpx;
  margin-bottom: 24rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  margin-left: 16rpx;
  font-size: 28rpx;
  color: #333;
}

.clear-btn {
  padding: 8rpx;
}

.list-container {
  padding: 20rpx 30rpx;
}

page {
  background-color: #f0f3f8;
  height: 100%;
}

.drill-card {
  background: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;

    .header-left {
      display: flex;
      align-items: center;
      gap: 15rpx;

      .drill-date {
        font-size: 21px;
        font-weight: 700;
        color: #4f4e4e;
        background: linear-gradient(to right, #0052d9 50%, #ff9900 99.9%);
        -webkit-background-clip: text;
        color: transparent;
      }
    }

    .status-tag {
      padding: 8rpx 20rpx;
      border-radius: 40rpx;
      font-size: 24rpx;
      display: flex;
      color: #f1f1f1;
      align-items: center;
      gap: 8rpx;
    }
  }
  .header-right {
    position: relative;
    left: 5rpx;
    .editBox {
      position: absolute;
      right: 0;
      top: 60rpx;
      background-color: #fff;
      width: 130rpx;
      border-radius: 8rpx;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
      z-index: 10;
      overflow: hidden;
      animation: fadeIn 0.3s ease;

      .editBox-item {
        padding: 16rpx;
        text-align: center;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f5f5f5;
        }

        .editBox-item-text {
          font-size: 25rpx;
          color: #333;
        }
      }
    }
  }

  .drill-image {
    width: 100%;
    height: 360rpx;
    border-radius: 8rpx 8rpx 0 0;
  }

  .card-body {
    padding: 20rpx;
    .status-tag {
      padding: 8rpx 20rpx;
      border-radius: 40rpx;
      font-size: 24rpx;
      display: flex;
      color: #f1f1f1;
      align-items: center;
      gap: 8rpx;
      width: 150rpx;
      position: relative;
      top: -65rpx;
      left: 495rpx;
    }
    .drill-title {
      display: block;
      font-size: 32rpx;
      color: #1a1a1a;
      font-weight: 600;
      margin-bottom: 80rpx;
    }

    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20rpx;
      margin-bottom: 25rpx;
      margin-top: -50rpx;
      .info-item {
        display: flex;
        align-items: center;
        gap: 12rpx;
        background: #fcf8e8;
        padding: 15rpx;
        border-radius: 8rpx;

        .info-content {
          display: flex;
          flex-direction: column;

          .info-label {
            font-size: 24rpx;
            color: #4f4e4e;
          }

          .info-value {
            font-size: 28rpx;
            color: #1a1a1a;
            font-weight: 500;
          }
        }
      }
    }

    .meta-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
        font-size: 26rpx;
        color: #4f4e4e;
      }
    }

    .duration-box {
      display: flex;
      align-items: center;
      gap: 12rpx;
      padding: 15rpx;
      background: #f1f1f1;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #1a1a1a;
    }
  }
}
</style>
